//
//  NKCreatAnnotationViewController.m
//  NKMapTest
//
//  Created by SongGang on 2017/4/6.
//  Copyright © 2017年 NK. All rights reserved.
//

#import "NKCreatAnnotationViewController.h"

@interface NKCreatAnnotationViewController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong)  UIImageView *imageView;
// 录音地址
@property (nonatomic, copy)  NSString *recordPath;
@property (nonatomic, weak)  UIButton *playButton;
@end

@implementation NKCreatAnnotationViewController

- (UIImageView *)imageView {

    if (!_imageView) {
        _imageView =  [[UIImageView alloc] initWithFrame:CGRectMake(20, 40, NKScreenWidth - 40, NKScreenHeight - 150 - 80)];
        [self.view addSubview:_imageView];
    }
    return _imageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    
}

- (void)initView {

    self.view.backgroundColor = [UIColor whiteColor];
    
    // 录音
    UIButton *audioButton = [UIButton buttonWithType:UIButtonTypeCustom];
    audioButton.frame = CGRectMake(40, NKScreenHeight - 150, 40, 40);
    [audioButton setImage:[UIImage imageNamed:@"audio"] forState:UIControlStateNormal];
    [audioButton addTarget:self action:@selector(audioStart:) forControlEvents:UIControlEventTouchUpInside];
    audioButton.selected = NO;
    [self.view addSubview:audioButton];
    
    // 拍照
    UIButton *cameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cameraButton.frame = CGRectMake(NKScreenWidth -40 - 40, NKScreenHeight - 150, 40, 40);
    [cameraButton setImage:[UIImage imageNamed:@"camera"] forState:UIControlStateNormal];
    [cameraButton addTarget:self action:@selector(goToCamera) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cameraButton];

    UILabel *statesLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, NKScreenHeight - 145, 200, 30)];
    statesLabel.NK_centerX = self.view.NK_centerX;
    statesLabel.text = @"注意：保存之前务必录音或拍照";
    statesLabel.textColor = NKBlueColor;
    statesLabel.font = [UIFont systemFontOfSize:13];
    statesLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:statesLabel];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(40, NKScreenHeight -  80, 40, 40);
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
     [cancelButton setTitleColor:NKBlueColor forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelButton];
    
    UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    playButton.frame = CGRectMake(40, NKScreenHeight -  80, 40, 40);
    playButton.NK_centerX = self.view.NK_centerX;
    [playButton setTitle:@"播放" forState:UIControlStateNormal];
    [playButton setTitleColor:NKBlueColor forState:UIControlStateNormal];
    playButton.hidden = YES;
    self.playButton = playButton;
    [playButton addTarget:self action:@selector(playAudio) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:playButton];
    
    
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    saveButton.frame = CGRectMake(NKScreenWidth -40 - 40, NKScreenHeight - 80, 40, 40);
     [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton setTitleColor:NKBlueColor forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];

}

// 拍照
- (void)goToCamera {
    
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    self.imageView.image = image;    
}

// 开始录音或者停止
- (void)audioStart:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    
    __weak typeof(self) weakSelf = self;
    
    if (sender.selected) {
        
        // 先创建目录用于保存
        [FileHelper filePathWithPath:self.pathName];
        // 创建录音文件名称
        NSString *fileName = [self.pathName stringByAppendingPathComponent:[EMCDDeviceManager creatFileNameWithDate]];
        [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error){
            
            if (error) {
                
            }else {
                
                weakSelf.playButton.hidden = YES;
                [sender setImage:[UIImage imageNamed:@"audioing"] forState:UIControlStateNormal];
                
            }
        }];
        
    }else {
        
        
        [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
            if (error) {
                
                
                NSLog(@"%@", error);
                
            }else {
                
                [sender setImage:[UIImage imageNamed:@"audio"] forState:UIControlStateNormal];
                weakSelf.recordPath = recordPath;
                weakSelf.playButton.hidden = NO;
            }
        }];
    }
}

// 播放录音
- (void)playAudio {
        
    [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath: self.recordPath completion:^(NSError *error) {
        
        if (error) {
            
            NSLog(@"%@", error);
            
        }else {
            
            
        }
    }];
    
    
}

- (void)saveView {

     NSString *imagePath = @"nil";
    
    if ( self.imageView.image != nil) {
        // 把图片写入沙盒
        imagePath = [FileHelper filePathWithPath:self.pathName];
        imagePath = [imagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",[FileHelper creatFileNameWithDate]]];
        //其中参数0.5表示压缩比例，1表示不压缩，数值越小压缩比例越大
        [UIImageJPEGRepresentation(self.imageView.image, 0.5) writeToFile:imagePath  atomically:YES];
        imagePath = [FileHelper fileNameWithShortPath:imagePath];
    }
    
    //由于沙盒的位置变化，只保存NKMap后的路径
    self.recordPath = [FileHelper fileNameWithShortPath:self.recordPath];
   
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.currentLocation forKey:@"currentLocation"];
    [dict setObject:imagePath forKey:@"imagePath"];
    if (self.recordPath != nil) {
        [dict setObject:self.recordPath forKey:@"audioPath"];
    }else {
        [dict setObject:@"nil" forKey:@"audioPath"];
    }
    
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationNameWithAddAnnotationPonit object:self userInfo:dict];
    }];
}

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)closeView {

    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
